/*
 * Copyright (c) 2008 Universidade Federal de Campina Grande
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package br.edu.ufcg.threadcontrol.aspects;

public aspect ThreadSleeperAspect {
	
		/**
		 * Before a call to any method invoked inside any run method of the application, 
		 * maybe make the current Thread sleep. This sleep will depend on a random method chosen.
		 * 
		 */
//		before(): call (* *(..))  && withincode (* *..*.run()) { 
//			makeThreadSleepIfItIsHerTurn();
//		}
		
		/**
		 * Chooses a random number between 1 and 3, and if this number is 3, the current
		 * thread sleeps for a random time, between 100 and 200 milliseconds. 
		 */
		private void makeThreadSleepIfItIsHerTurn(){
			int randomNumber = chooseRandomNumberBetweenLimits(1,3);
			if (randomNumber==3){
				long timeToSleep = chooseRandomNumberBetweenLimits(100, 200);
				try {
					Thread.sleep(timeToSleep);
				} catch (InterruptedException ie){
					ie.printStackTrace();
				}
			}
		}
		
		/**
		 * Chooses a random number between min and max, including them.
		 * @param min The minimal limit.
		 * @param max The maximum limit
		 * @return the random number chosen.
		 */
		private static  int chooseRandomNumberBetweenLimits (int min, int max){
			int numberOfOptions = max - min + 1;
			int randomNumber = ((int) (numberOfOptions * Math.random())) % (numberOfOptions) + min;
			return randomNumber;
		}	

}
